package com.irishud.hudnavi.ar_navi;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.google.gson.Gson;
import com.irishud.hudnavi.udp.UdpRxThread;
import com.irishud.hudnavi.udp.UdpTxThread;

import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.util.Timer;
import java.util.TimerTask;

import de.greenrobot.event.EventBus;
import tcp.TcpServerSocketThread;

/**lxs-------------
 * 通信管理
 * Created by Administrator on 2016/10/14.
 */

public class ARHudComm {
    public interface DeviceConnetionListener{
        void deviceConnected();
        void deviceDisconnected();
    }

    public enum CommMode{
        Phone,
        Device
    };

    CommMode commMode;

    DeviceConnetionListener deviceConnetionListener;

    String TAG = "ARHudComm";
    UdpTxThread arUdp;
    UdpTxThread broadcastUdp;// 广播
    String deviceIpAddr = "";
    boolean deviceIsConnected = false; // 设备连接状态
    long heartbeatTick;
    Timer heartbeatCheckTimer;
    UdpRxThread deviceHeartbeat;
    TcpServerSocketThread tcpServerSocketThread;
    boolean navi_data_debug_mode = false;// 导航AR 调试模式

    static ARHudComm instance =new ARHudComm();

    private ARHudComm(){}

    public static ARHudComm getInstance(){
        return instance;
    }

    public boolean deviceIsConnected(){
        return deviceIsConnected;
    }

    public void setDeviceConnetionListener(DeviceConnetionListener listener){
        this.deviceConnetionListener = listener;
    }

    public void enableNaviDebugMode(){
        navi_data_debug_mode = true;
    }

    public void disableNaviDebugMode(){
        navi_data_debug_mode = false;
    }

    public boolean isNavi_data_debug_mode(){
        return  navi_data_debug_mode;
    }

    public void init(CommMode mode){
        commMode = mode;
        if(mode == CommMode.Phone){
            broadcastUdp = new UdpTxThread("255.255.255.255",18000);

            deviceHeartbeat = new UdpRxThread("255.255.255.255",60002);
            deviceHeartbeat.setUdpRxListener(new UdpRxThread.UdpReceivedListener() {
                @Override
                public void onUdpReceived(byte[] data, int len) {
                    String jsonStr = new String(data,0,len) ;
                    ProtoMsg protoMsg = JSON.parseObject(jsonStr,ProtoMsg.class);
                    if(protoMsg.action.equals("device.heartbeat")){// 设备心跳
                        Log.i(TAG,"=========> 收到设备心跳");//每隔5s左右会收到一个设备心跳信息
                        heartbeatTick = System.currentTimeMillis();
                    }
                }
            });
            heartbeatCheckTimer = new Timer();
            heartbeatCheckTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    long now = System.currentTimeMillis();
                    long delta = now - heartbeatTick;
                    if(delta >= 10*1000){// 超过10s没有收到设备心跳，说明设备连接已经断开!
                        Log.e(TAG,"xxxxxxx 设备连接已经断开 xxxxxxx");
                        deviceIsConnected = false;
                        if(deviceConnetionListener!=null){
                            deviceConnetionListener.deviceDisconnected();
                        }
                        EventBus.getDefault().post(new DeviceConnectionEvent(DeviceConnectionEvent.Disconnected));
                    }else{
                        Log.i(TAG,"======= 设备已连接! =======");
                        deviceIsConnected = true;
                        if(deviceConnetionListener!=null){
                            deviceConnetionListener.deviceConnected();
                        }
                        EventBus.getDefault().post(new DeviceConnectionEvent(DeviceConnectionEvent.Connected));
                    }
                }
            },1000,5*1000);

            final Gson gson = new Gson();
            tcpServerSocketThread = new TcpServerSocketThread(50002);
            tcpServerSocketThread.setReceiveListener(new TcpServerSocketThread.ReceiveListener() {
                @Override
                public void onSocketReceived(TcpServerSocketThread server, byte[] data, int len) {
                    try{ // 由于断包，粘包的问题，这里有时候会报解析异常
                        String jsonStr = new String(data,0,len) ;
                        jsonStr = jsonStr.trim();
                        ProtoMsg protoMsg = gson.fromJson(jsonStr,ProtoMsg.class);
                        if(protoMsg.action.equals("device.heartbeat")){// 设备心跳
                            Log.i(TAG,"=========> 收到设备心跳");
                            heartbeatTick = System.currentTimeMillis();
                        }

                        if(protoMsg.action.equals("device.settings")){

                        }

                    }catch (JSONException ex){
                        Log.e("json error",ex.getMessage());
                    }
                }
            });

            tcpServerSocketThread.setAcceptConnectionListener(new TcpServerSocketThread.AcceptConnectionListener() {
                @Override
                public void onNewClientSocketConnected(InetAddress clientAddr) {
                    if(arUdp!=null){arUdp.stop();}
                    arUdp = new UdpTxThread(clientAddr.getHostAddress(),18000);//启动UDP 线程，发送到18000 AR端口

                    ProtoMsg request = new ProtoMsg("get_device_settings","");// 查询设备信息
                    tcpServerSocketThread.equeueToSend(request.toBytes());
                }
            });
        }else if(mode == CommMode.Device){

        }
    }

    public void setAR_UdpThread(UdpTxThread txThread){
        if(this.arUdp!=null){
            arUdp.stop();
        }
        this.arUdp = txThread;
    }

    public void sendToAR(ByteBuffer buffer){

        if(arUdp!=null){
            arUdp.enqueue(buffer);
        }

        if(commMode == CommMode.Phone){
            if(navi_data_debug_mode){
                if(broadcastUdp!=null){
                    broadcastUdp.enqueue(buffer);
                }
            }
        }
    }

    public void sendToHud(ByteBuffer buffer){
        tcpServerSocketThread.equeueToSend(buffer);
    }

    public void destroy(){
        if(arUdp!=null)arUdp.stop();
        tcpServerSocketThread.stop();
    }
	
	public static class HudAction {

        public static  final String  NAV_UPDATE_INFO   = "updateNaviInfo";    //
        public static  final String  NAV_UPDATE_SPEED  = "updateNaviSpeed";    //
        public static  final String  SYS_OTA_UPDATE    = "sys_ota_update";     //ota升级
        public static  final String  NAV_INDICATOR     = "nav_indicator";    //导航指示信息NAV_INDICATOR
        public static  final String  ADJUST_LIGHT      = "adjust_light";     //亮度调节
        public static  final String  AUTO_ADJUST_LIGHT = "auto_adjust_light";//是否自动调节
        public static  final String  ADJUST_MOTOR      = "adjust_motor";     //调节马达
    }

    public void send2Hud(String action,Object settings){
        ProtoMsg protoMsg = new ProtoMsg(action, JSON.toJSONString(settings));
        ARHudComm.getInstance().sendToHud(protoMsg.toBytes());
    }
}
